package com.mygame.game_server.cmdHandle;

import com.mygame.game_server.msg.GameMsgProtocol;
import com.mygame.game_server.rank.RankItem;
import com.mygame.game_server.rank.RankService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;

/**
 * 排行榜处理器
 *
 */
public class GetRankCmdHandler implements ICmdHandler<GameMsgProtocol.GetRankCmd> {

    private final static Logger logger = LoggerFactory.getLogger(GetRankCmdHandler.class);

    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.GetRankCmd cmd) {
        if (null == ctx || null == cmd) {
            return;
        }
        RankService.getInstance().getRank((rankItems) -> {
            if (null == rankItems) {
                rankItems = Collections.emptyList();
            }

            GameMsgProtocol.GetRankResult.Builder resultBuilder = GameMsgProtocol.GetRankResult.newBuilder();

            for (RankItem rankItem : rankItems) {
                if (null == rankItem) {
                    continue;
                }


                GameMsgProtocol.GetRankResult.RankItem.Builder rankItemBulider = GameMsgProtocol.GetRankResult.RankItem.newBuilder();
                rankItemBulider.setRankId(rankItem.rankId);
                rankItemBulider.setHeroAvatar(rankItem.heroAvatar);
                rankItemBulider.setUserId(rankItem.userId);
                rankItemBulider.setUserName(rankItem.userName);
                rankItemBulider.setWin(rankItem.win);


                resultBuilder.addRankItem(rankItemBulider);
            }
            GameMsgProtocol.GetRankResult newResult = resultBuilder.build();
            ctx.writeAndFlush(newResult);
            logger.info("发送排名");
            return null;
        });

    }
}
